package validation

import (
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var (
	uniT *ut.UniversalTranslator
	trans ut.Translator
)

func init() {
	//注册翻译器
	validate, ok := binding.Validator.Engine().(*validator.Validate)
	if ok {
		zhT := zh.New()
		uniT = ut.New(zhT, zhT)
		trans, _ = uniT.GetTranslator("zh")

		zh_translations.RegisterDefaultTranslations(validate, trans)

		validate.RegisterValidation("phoneValidator", PhoneValidator)
		validate.RegisterValidation("emailValidator", EmailValidator)

		regTranslationMsg(validate, "phoneValidator", "格式不正确")
		regTranslationMsg(validate, "emailValidator", "格式不正确")
	}
}

func Trans(err error)(result string){
	errors, ok := err.(validator.ValidationErrors)
	if ok{
		for key, err := range errors{
			result += err.Translate(trans)
			if key != len(errors)-1{
				result += ", "
			}
		}
	}else{
		result = err.Error()
	}
	return result
}

// 自定义验证规则的翻译
func regTranslationMsg(v *validator.Validate, tag, errMsg string) {
	_ = v.RegisterTranslation(tag, trans, func(ut ut.Translator) error {
		return ut.Add(tag, "{0} "+errMsg, true)
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T(tag, fe.Field())
		return t
	})
}

